package com.android.questions.util.sound;

import android.content.Context;
import android.media.MediaPlayer;

import com.android.base.util.DQLog;
import com.android.questions.R;
import com.android.questions.config.AppConfig;

/**
 * FileName: GoldMusicManager
 * Author: admin
 * Date: 2021/11/9 14:54
 * Description:
 */
public class GoldMusicManager {

    private MediaPlayer mediaPlayer;

    private static volatile GoldMusicManager instance = null;

    private GoldMusicManager(Context context) {
        this.mediaPlayer = MediaPlayer.create(context, R.raw.ui_gold);
        initMediaPlayer();
    }

    public static GoldMusicManager getInstance(Context context) {
        if (instance == null) {
            synchronized (GoldMusicManager.class) {
                if (instance == null) {
                    instance = new GoldMusicManager(context);
                }
            }
        }
        return instance;
    }

    private void initMediaPlayer() {
        try {
            mediaPlayer.setLooping(false);//设置为循环播放
//            mediaPlayer.prepare();//初始化播放器MediaPlayer //MediaPlayer.create已经帮你prepare了
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void start() {
        //如果没在播放中，立刻开始播放。
        if (!AppConfig.getGameSound()) {
            return;
        }
        if (mediaPlayer != null) {
            try {
                if (!mediaPlayer.isPlaying()) {
                    mediaPlayer.start();
                }
            } catch (Exception e) {
                DQLog.e("e:" + e.toString());
            }
        }
    }

    public void pause() {
        if (mediaPlayer != null) {
            //如果在播放中，立刻暂停。
            try {
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.pause();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void reset() {
        if (mediaPlayer != null) {
            //如果在播放中，立刻停止。
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.reset();
                initMediaPlayer();//初始化播放器 MediaPlayer
            }
        }
    }

    public void release() {
        try {
            if (mediaPlayer != null) {
                mediaPlayer.stop();
                mediaPlayer.release();
                mediaPlayer = null;
                instance = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
